
from django import forms
from django.core.exceptions import ValidationError
from web import models
from web.forms.bootstrap import BootStrapForm
from web.forms.widgets import ColorRadioSelect
class ProjectModelForm(BootStrapForm,forms.ModelForm):
    # desc = forms.CharField(widget=forms.Textarea())
    bootstrap_class_exclude = ['color']
    def __init__(self, request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ['name','color','desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': "color-radio"}),
        }

    def clean_name(self):
        """项目校验"""
        # 1.项目名称重复
        name = self.cleaned_data.get('name')
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError("项目名称已存在")
        #2.当前用户是否还有额度创建
        #最多创建几个 self.request.tracer.price_policy.project_num
        #已经创建几个
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请升级套餐')
        #3.当前用户是否有权限创建
        return name


